//
//  AiCustomDao.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/10/31.
//

import Foundation
import GRDB
class AiCustomDao {
    func getList() async throws -> [AiCustomBean] {
        return try await DatabaseRecordManager.shared.dbQueue.read { db in
            try AiCustomBean
                .order(Column("sort").asc)
                .fetchAll(db)
        }
    }
    
    func get(objectId: String)  async throws -> AiCustomBean? {
        return try await DatabaseRecordManager.shared.dbQueue.read { db in
            let list = try AiCustomBean
                .filter(Column("objectId") == objectId)
                .limit(1)
                .order(Column("sort").asc)
                .fetchAll(db)
            if list.isEmpty {
                return nil
            } else {
                return list[0]
            }
        }
    }
    
    func get(host: String, model: String, token: String)  async throws -> AiCustomBean? {
        return try await DatabaseRecordManager.shared.dbQueue.read { db in
            let list = try AiCustomBean
                .filter(Column("host") == host)
                .filter(Column("model") == model)
                .filter(Column("token") == token)
                .limit(1)
                .order(Column("sort").asc)
                .fetchAll(db)
            if list.isEmpty {
                return nil
            } else {
                return list[0]
            }
        }
    }
    
    
    func doSave(bean: AiCustomBean) async throws {
        try await DatabaseRecordManager.shared.dbQueue.write { db in
            if (bean.objectId ?? "").isEmpty == true {
                bean.objectId = UUID().uuidString
                try bean.insert(db)
            } else {
                try bean.update(db)
            }
        }
    }
    
    func insert(bean: AiCustomBean) async throws {
        try await DatabaseRecordManager.shared.dbQueue.write { db in
            try bean.insert(db)
        }
    }
    
    func doDel(bean: AiCustomBean) async throws {
        _ = try await DatabaseRecordManager.shared.dbQueue.write { db in
            try AiCustomBean
                .filter(Column("objectId") == bean.objectId)
                .deleteAll(db)
        }
    }
}
